import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import { showToast } from "vant";
import router from "@/router";
import store from "@/store";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = [
  "/my/login",
  "/my/index",
  "/index",
  "/learning",
  "/training",
  "/test",
  "/test/info",
  "/test/myexams",
  "/test/analysis",
]; // no redirect whitelist

// 检查用户是否有权限访问该路由
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    // 如果路由没有设置 roles，则默认所有人都可以访问
    return true;
  }
}

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === "/my/login") {
      next({ path: "/my/index" });
      NProgress.done();
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        // 检查用户是否有权限访问该路由
        if (hasPermission(store.getters.roles, to)) {
          next();
        } else {
          showToast({
            message: "您没有权限访问该页面",
            type: "fail",
            duration: 5000,
          });
          // 不跳转到404，而是停留在当前页面
          next(false);
          NProgress.done();
        }
      } else {
        try {
          // 获取用户信息
          const { roles } = await store.dispatch("user/getInfo");

          // 检查用户是否有权限访问该路由
          if (hasPermission(roles, to)) {
            next({ ...to, replace: true });
          } else {
            showToast({
              message: "您没有权限访问该页面",
              type: "fail",
              duration: 5000,
            });
            // 不跳转到404，而是跳转到首页或其他有权限的页面
            next("/home");
            NProgress.done();
          }
        } catch (error) {
          await store.dispatch("user/resetToken");
          showToast({
            message: error || "发生错误",
            type: "fail",
          });
          next(`/my/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      showToast({
        message: "请返回登陆！",
        type: "fail",
        duration: 5000,
      });
      next(`/my/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
